package cn.angis.system.service;

import cn.angis.common.constant.Constant;
import cn.angis.db.service.BaseService;
import cn.angis.system.dto.output.DictOutput;
import cn.angis.system.dtomapper.DictStruct;
import cn.angis.system.model.Dict;
import cn.hutool.core.util.StrUtil;
import org.noear.solon.annotation.ProxyComponent;
import org.noear.solon.data.annotation.Cache;
import org.sagacity.sqltoy.model.EntityQuery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 字典数据表服务
* @author angis.cn
* @Date 2023-01-05
*/
@ProxyComponent
public class DictService extends BaseService<Dict> {
    public List<Dict> listByType(String type) {
        return dao.findEntity(Dict.class, EntityQuery.create().select("label", "value")
                .where("#[type=:type] #[and status=:status]")
                .values(type,Constant.ENABLE).orderBy("status"));
    }

    @Cache(key=Constant.CACHE_DICT_MAP, tags = Constant.CACHE_DICT_MAP)
    private Map<String, List<Dict>> getMapDict() {
        Map<String, List<Dict>> dictMap = new HashMap<>();
        for (Dict dict : listAll()){
            List<Dict> dictList = dictMap.get(dict.getType());
            if (dictList != null){
                dictList.add(dict);
            }else{
                dictMap.put(dict.getType(), new ArrayList<Dict>(List.of(dict)));
            }
        }
        return dictMap;
    }

    public Map<String, List<DictOutput>> getMapByTypes(String types) {
        Map<String, List<DictOutput>> result = new HashMap<>();
        if (StrUtil.isNotBlank(types)) {
            String[] typeArr = types.split(",");
            for (String type : typeArr) {
                result.put(type.replace("-", ""), getListByType(type));
            }
        }
        return result;
    }

    private List<DictOutput> getListByType(String type) {
        return DictStruct.INSTANCE.toOutputList(getMapDict().get(type));
    }

    private List<Dict> listAll() {
        return dao.findEntity(Dict.class, EntityQuery.create().select("label", "value", "type")
                .where("#[status=:status]")
                .values(Constant.ENABLE).orderBy("status"));
    }
}